const express = require('express');
const path = require('path');
const session = require('express-session');
const emailRoutes = require('./routes/email');
const initDatabase = require('./config/init-db');
const bottleRoutes = require('./routes/bottle');
const authRoutes = require('./routes/auth');
const emailScheduler = require('./services/scheduler');
const messageRoutes = require('./routes/message');

const app = express();

// 配置 session 中间件
app.use(session({
    secret: process.env.SESSION_SECRET || 'your-secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: process.env.NODE_ENV === 'production',
        maxAge: 24 * 60 * 60 * 1000 // 24小时
    }
}));

// 配置中间件
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());

// 添加认证中间件
const authMiddleware = (req, res, next) => {
    if (!req.session.userId && req.path !== '/api/auth/login' && req.path !== '/api/auth/send-code') {
        return res.status(401).json({ error: '请先登录' });
    }
    next();
};

// 路由配置
app.use('/api/auth', authRoutes);
app.use('/api', authMiddleware); // 添加认证中间件
app.use('/api', emailRoutes);
app.use('/api/bottle', bottleRoutes);
app.use('/api/messages', messageRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: '服务器内部错误' });
});

// 404 处理
app.use((req, res) => {
    res.status(404).json({ error: '未找到请求的资源' });
});

// 启动服务器
const PORT = process.env.PORT || 3000;

// 异步启动服务器
async function startServer() {
    try {
        // 初始化数据库
        const dbInitialized = await initDatabase();
        if (!dbInitialized) {
            console.error('数据库初始化失败，服务器将继续启动但某些功能可能不可用');
        }

        // 初始化邮件调度器
        await emailScheduler.initialize();

        // 启动服务器
        app.listen(PORT, () => {
            console.log(`服务器运行在 http://localhost:${PORT}`);
        });
    } catch (error) {
        console.error('服务器启动失败:', error);
        process.exit(1);
    }
}

startServer(); 